import tools from '../utils/tools';
import extention from '../utils/extention';
import showBoardItemTpl from '../templates/show_board_item.tpl';

@extention
@tools
export default class TabNav {
    constructor(phoneData) {
        this.name = 'TabNav';
        this.$tab = $('.J_tab');
        this.$board = $('.J_board');
        this.phoneData = phoneData;
        this.htmlCache = {};
    }

    init() {
        this.bindEvent();
    }

    bindEvent() {
        this.$tab.on('click', '.tab-item', this.onTabClick.bind(this))
    }
    onTabClick(ev) {
        let target = TabNav.getEvTarget(ev),
            tagName = target.tagName;
        if (tagName === 'A') {
            let $target = $(target),
                keyword = $target.data('field'),
                searchData = this.getSearchData('tab', this.phoneData, keyword);
            this.changeTab($target, 'current');
            this.makeList(searchData, keyword);
        }
    }
    makeList(data, field) {
        let list = '';
        if (!this.htmlCache[field]) {
            data.forEach((item, index) => {
                list += TabNav.tplReplace(showBoardItemTpl, {
                    id: item.id,
                    isFirst: index % 5 === 0 ? 'first' : '',
                    phone_name: item.phone_name,
                    pic: JSON.parse(item.pics)[0][0][0],
                    slogan: item.slogan.substring(0, 10),
                    default_price: item.default_price
                })
            });
            this.htmlCache[field] = list;
        }
        this.$board.html(this.htmlCache[field]);
    }
}